package com.qiudaozhang.jblog.frontend.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.qiudaozhang.jblog.model.Article;
import com.qiudaozhang.jblog.model.ArticleInfo;
import com.qiudaozhang.jblog.model.Category;
import com.qiudaozhang.jblog.article.service.ArticleService;
import com.qiudaozhang.jblog.article.service.CategoryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * 文章前端入口
 */
@Controller
@RequestMapping("article")
public class ArticleController {


    @Reference(url = "${article.service.provider.url}", version = "${service.version}", group = "${dubbo.group}")
    private ArticleService articleService;
    @Reference(url = "${article.service.provider.url}", version = "${service.version}", group = "${dubbo.group}")
    private CategoryService categoryService;

    @RequestMapping("list")
    public String list(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize,
                       Model model){
        handleParam(pageNum,pageSize);
        pageSize = 10;
        PageInfo<ArticleInfo> p = articleService.queryPageOrderByUpdateTimeDesc(pageNum, pageSize);
        model.addAttribute("p",p);
        // 查询所有分类信息
        List<Category> categories = categoryService.selectAll();
        model.addAttribute("categories",categories);

        return "index";
    }

    private void handleParam(Integer pageNum, Integer pageSize) {
        if( pageNum < 1){
            throw  new RuntimeException("客户恶意提供分页参数：当前页码");
        }
        if(pageSize > 20 || pageSize < 1){
            throw  new RuntimeException("客户恶意提供分页参数：分页大小");
        }

    }

    @RequestMapping("get/{articleId}")
    public String get(@PathVariable("articleId") Integer articleId,Model model){
        ArticleInfo article = articleService.getDetail(articleId);
        model.addAttribute("article",article);
        model.addAttribute("categories",categoryService.selectAll());
        return "post";
    }

    @RequestMapping("search")
    public String search(@RequestParam("search") String search, Model model){
        PageInfo<ArticleInfo> p = articleService.queryPageOrderBySearch(search,1, 10);
        model.addAttribute("p",p);
        // 查询所有分类信息
        List<Category> categories = categoryService.selectAll();
        model.addAttribute("categories",categories);
        return "index";
    }
}
